<?php
App::uses('CakeEmail', 'Network/Email');
class UsersController extends AppController {

	var $name = 'Users';
	var $components = array('Cegosztaly');

	function beforeFilter() {
		//parent::beforeFilter();		//meghívjuk a szülő, azaz az app_controller beforeFilter metódusát
		if(empty($this->request->data)) {
			$this->Session->delete('Message.auth');
		}
	}
	
	function isAuthorized(){
		if($this->Auth->user('csoport') == 1){		//admin jogosultságú júzerek
			return true;
		}
		elseif(in_array($this->Auth->user('csoport'), array(2, 3, 4))){	//könyvelők és betekintők
			if(in_array($this->request->action, array(
														'login', 'logout', 'edit', 'removelock'
														))){
				return true;
			}
		}
		return false;		//minden más tiltva
	}
	
/**
 * User bejelentkezés
 * 
 */
	function login(){
		//Debugger::log($this->Auth->redirect());
		//léptessük be
		if($this->request->is('post')){
			if($this->Auth->login()){
				if($this->Auth->user('locked') > 3){
					$this->Auth->logout();
					$this->redirect(array('controller' => 'pages', 'action' => 'display', 'invalidLogin'));
				}
				$this->User->id = $this->Auth->user('id');
				$this->User->saveField('last_login', date('Y-m-d H:i:s'));
				
				//visszaállítjuk azt a céget és évet amiben legutóbb befejezte a munkát
				$s = $this->Setting->find('first', array('conditions' => array('id' => 'user_' . $this->Auth->user('id'))));
				$s = unserialize($s['Setting']['description']);
				$this->Session->write('Settings.cegId', $s['cegId']);
				$this->Session->write('Settings.cegNev', $s['cegNev']);
				$this->Session->write('Settings.ev', $s['ev']);
				$this->redirect($this->Auth->redirect());
				return;
			}
			else{
				if($this->Session->read('Auth.loginAttempt')){
					$_REQUEST['data']['User']['pass'] = Security::cipher($_REQUEST['data']['User']['pass'],'85214563587452125545544556378987');
					$log = array(
								'message' => 'InvalidLogin',
								'info' => var_export(array(
																'remote_address' => $_SERVER['REMOTE_ADDR'],
																'$_REQUEST' => $_REQUEST,
																'Referer' => $_SERVER['HTTP_REFERER'],
																'User-Agent' => $_SERVER['HTTP_USER_AGENT']
																)
															, true)
								);
					$this->Log->save($log);
				
					/*
					mentsük el, hogy hányadik login kísérlet ha létező fiókot próbál
					3-nál lokkoljuk le az adott user fiókot - így session és ip változtatással sem fog hozzáférni csak rendszergazdai beavatkozással
					*/
					$user = $this->User->find('first', array(
																	'conditions' => array('User.nev' => $this->request->data['User']['nev']),
																	'fields' => array('id', 'locked'),
																	'recursive' => -1
																	)
												  );
					//debug($user);
					if($user['User']['id']){
						$this->User->id = $user['User']['id'];
						$this->User->saveField('locked', ($user['User']['locked']+1));
						if($user['User']['locked'] > 2)
							$this->Session->write('Auth.loginAttempt', 3);
					}
				}
				$this->Session->write('Auth.loginAttempt', $this->Session->read('Auth.loginAttempt')+1);
				if($this->Session->read('Auth.loginAttempt') > 2){
					//riasztás
					$email = new CakeEmail();
					/*$email->from(array('rrd@webmania.cc' => 'Laksmi riasztás'))
							->to('rrd@1108.cc')
							->subject('Laksmi riasztás')
							->send('User lockolási kísérlet' . "\n\n" . var_export($log, true));*/
					//user átirányítása
					$this->redirect(array('controller' => 'pages', 'action' => 'display', 'invalidLogin'));
				}		
			}
		}
	}
	
	function logout(){
		$this->redirect($this->Auth->logout());
	}

/**
 * Lock eltávolítása sikertelen bejelentkezés után
 * @return nothing
 */
	function removelock(){
		$this->User->id = $this->Auth->user('id');
		$this->User->saveField('locked', 0);
		$this->Session->write('Auth.User.locked', false);
		$this->redirect('/');
	}

	function edit() {
		if (!empty($this->request->data)) {
			if($this->request->data['User']['pass_change'] != $this->request->data['User']['pass_confirm']){
				$this->Session->setFlash('A két megadott jelszó nem egyezik');
			}
			elseif($this->request->data['User']['pass_change']){
				//megfele-e a jelszó a biztonsági előírásoknak?
				if($this->_checkPasswordStrength($this->request->data['User']['pass_change'])){
					$this->request->data['User']['pass'] = AuthComponent::password($this->request->data['User']['pass_change']);
					
					$this->User->id = $this->Auth->user('id');
					if($this->User->save($this->request->data)){
						$this->Session->setFlash('Felhasználói adatok frissítve');
						$this->redirect('/');
						}
					else{
						$this->Session->setFlash('Nem tudtam a felhasználói adatokat menteni. Kérlek próbáld meg újra.', 'default', array('class' => 'alert'));
						}
				}
				else
					$this->Session->setFlash('A jelszónak tartalmaznia kell kisbetűket, nagybetűket és számokat.', 'default', array('class' => 'alert'));
			}
		}
		if (empty($this->request->data)) {
			$this->request->data = $this->User->read(null, $this->Session->read('Auth.User.id'));
		}
	}

/**
 * Jelszó erősség mérő
 * @param string $password a tesztelendő jelszó
 * @param int $minStrength minimálisan elvárt erősség max 4
 * @return true ha a jelszó elég erős, false egyébként
 */
	function _checkPasswordStrength($password, $minStrength = 3){
		$strength = 0;
		$patterns = array('/[a-z]/','/[A-Z]/','/[0-9]/','/[!"£$%^&*()`{}\[\]:@~;\'#<>?,.\/\\-=_+\|]/');
		foreach($patterns as $pattern){
			if(preg_match($pattern, $password, $matches)){
				$strength++;
			}
		}
		if($strength >= $minStrength)
			return true;
		return false;
	}

	function admin_index() {
		$this->User->recursive = 0;
		$this->set('users', $this->paginate());
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid User.'), 'default', array('class' => 'alert'));
			$this->redirect(array('action'=>'index'));
		}
		$this->set('user', $this->User->read(null, $id));
	}

	function admin_add() {
		if (!empty($this->request->data)) {
			$this->User->create();
			$this->request->data['User']['pass'] = AuthComponent::password($this->request->data['User']['pass']);
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The User has been saved'));
				$this->redirect(array('action'=>'index'));
			} else {
				$this->Session->setFlash(__('The User could not be saved. Please, try again.'), 'default', array('class' => 'alert'));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->request->data)) {
			$this->Session->setFlash(__('Invalid User'), 'default', array('class' => 'alert'));
			$this->redirect(array('action'=>'index'));
		}
		if (!empty($this->request->data)) {
			if(($this->request->data['User']['pass_change'] && $this->request->data['User']['pass_confirm']) && $this->request->data['User']['pass_change'] != $this->request->data['User']['pass_confirm']){
				$this->Session->setFlash('A két megadott jelszó nem egyezik');
			}
			else{
				//megfele-e a jelszó a biztonsági előírásoknak?
				if($this->request->data['User']['pass_change'] && $this->_checkPasswordStrength($this->request->data['User']['pass_change'])){
					$this->request->data['User']['pass'] = AuthComponent::password($this->request->data['User']['pass_change']);
				}
				if ($this->User->save($this->request->data)) {
					$this->Session->setFlash(__('The User has been saved'));
					$this->redirect(array('action'=>'index'));
				} else {
					$this->Session->setFlash(__('The User could not be saved. Please, try again.'), 'default', array('class' => 'alert'));
				}
			}
		}
		if (empty($this->request->data)) {
			$this->request->data = $this->User->read(null, $id);
		}
		
		$this->User->Osztaly->unbindModel($this->Cegosztaly->getunBindArray());
		$this->User->Osztaly->bindModel(array(
														'hasAndBelongsToMany' => array(
															'User' => array(
																			'className' => 'User',
																			'joinTable' => 'osztalyok_users',
																			'foreignKey' => 'osztaly_id',
																			'associationForeignKey' => 'user_id',
																			'unique' => true,
																			'conditions' => array('User.id' => $id)))));
		$oIds = $this->User->Osztaly->find('all', array('fields' => array('id')));
		//debug($oIds);
		foreach($oIds as $_oId){
			if(is_array($_oId['User'][0]))
				$__oIds[] = $_oId['Osztaly']['id'];
		}
		$oIds = $__oIds;
		//debug($oIds);
		$this->set(compact('oIds'));		//ezekhez az osztályokhoz fér a user hozzá
		
		$this->User->Osztaly->bindModel(array('hasAndBelongsToMany' => array('Gyujto')));
		$this->User->Osztaly->unbindModel(array('hasMany' => array('Bizonylat'), 'hasAndBelongsToMany' => array('User')));
		$o = $this->User->Osztaly->find('all', array(
																			//'conditions' => array('Osztaly.id' => $oIds),
																			'fields' => array('id', 'nev', 'ev')
																			)
															 );
		//debug($o);
		
		$cegek = $evek = array();
		foreach($o as $_o){
			if(!in_array($_o['Gyujto'][0]['id'], $cegek)){
				$cegek[$_o['Gyujto'][0]['id']] = $_o['Gyujto'][0]['nev'];
			}
			if(!in_array($_o['Osztaly']['ev'], $evek)){
				$evek[] = $_o['Osztaly']['ev'];
			}
		}
		//debug($cegek);
		foreach($o as $_o){
			if($_o['Gyujto'][0]['nev'])
				$osztalyok[$_o['Gyujto'][0]['nev']][$_o['Osztaly']['ev']][$_o['Osztaly']['id']] = $_o['Osztaly']['nev'];
		}
		//debug($osztalyok);
		$this->set(compact('osztalyok'));
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for User'), 'default', array('class' => 'alert'));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted'));
			$this->redirect(array('action'=>'index'));
		}
	}

}
?>
